package com.boot.ys.mybatisplus.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.boot.ys.mybatisplus.service.OSSFileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

@Service
public class OSSFileServiceImpl implements OSSFileService {

    private static String TYPESTR[] = {".png",".jpg",".bmp",".gif",".jpeg"};

    @Value("${env.endpoint}")
    private String endpoint;

    @Value("${env.AccessKeyID}")
    private String keyId;

    @Value("${env.AccessKeySecret}")
    private String keySecret;

    @Value("${env.filehost}")
    private String fileHost;

    @Value("${env.bucketname}")
    private String bucketName;

    /**
     * 实现阿里云OSS 文件上传 只上传图片
     * @param file
     * @return
     */
    @Override
    public String ossUpload(MultipartFile file) {

        OSSClient ossClient = null;
        String url = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClient(endpoint ,keyId,keySecret);
            boolean flag = false;
            //判断文件格式
            for(String type : TYPESTR){
                if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                return "图片格式不正确";
            }
            //判断文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image != null){
                System.err.println(String.valueOf(image.getHeight()));
                System.err.println(String.valueOf(image.getWidth()));
            } else{
                return "文件内容不正确";
            }
            //获取文件名称
            String filename = file.getOriginalFilename();
            //文件名字： lijin.shuai.jpg
            String ext = filename.substring(filename.lastIndexOf("."));
            String newName = UUID.randomUUID().toString() + ext;// ertyerxvnxrvjtcfhjktcfgh
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            String urlPath = fileHost + "/" + dataPath + "/" + newName;
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, urlPath, inputStream);
            url = "https://"+bucketName + "." + endpoint + "/" + urlPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

        return url;
    }


    /**
     * 上传第其他的 文件，没有做限制
     * @param file
     * @return
     */
    @Override
    public String uploadAll(MultipartFile file) {

        OSSClient ossClient = null;
        String url = null;
        try {
            ossClient = new OSSClient(endpoint ,keyId,keySecret);
            String filename = file.getOriginalFilename();
            String ext = filename.substring(filename.lastIndexOf("."));
            String newName = UUID.randomUUID().toString() + ext;// ertyerxvnxrvjtcfhjktcfgh
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            String urlPath = fileHost + "/" + dataPath + "/" + newName;
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, urlPath, inputStream);
            url = "https://"+bucketName + "." + endpoint + "/" + urlPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return url;
    }

    /**
     * 删除阿里云服务器上的图片
     */
    @Override
    public void deleteOssFile() {
        //真实项目里面应该是只删除数据库里面的地址数据
        // 获取oss目标文件夹
        String filehost = "avatar/2022/01/25/014ba92c-4cb4-4d69-90c6-0a5e214e3933.rar";
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endpoint ,keyId,keySecret);

            ossClient.deleteObject(bucketName,filehost);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }


}
